﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SXT.Utility;
using SXT.Party.PartyAdmin.BLL;
using System.Web.Services;
using SXT.Party.Utility;

namespace SXT.Party.PartyAdmin.Module.WorkTrends
{
    public partial class WorkTrendsEdit : EditPageBase
    {
        #region 属性
        /// <summary>
        /// ID
        /// </summary>
        public string KeyID
        {
            get
            {
                if (string.IsNullOrEmpty(this.PrimaryKeyID) && Microsoft.Security.Application.AntiXss.HtmlEncode(Request.QueryString["ID"]) != null)
                {
                    this.PrimaryKeyID = Microsoft.Security.Application.AntiXss.HtmlEncode(Request.QueryString["ID"].ToString());
                }
                return this.PrimaryKeyID;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public string PageType
        {
            get
            {
                return Microsoft.Security.Application.AntiXss.HtmlEncode(Request.QueryString["PageType"] ?? "");
            }
        }

        /// <summary>
        /// 页面标识
        /// </summary>
        public override string PageSign
        {
            get
            {
                if (!string.IsNullOrEmpty(this.PageType))
                    return "BranchTrends";
                else
                    return "WorkTrends";
            }
        }
        #endregion

        #region Page_Load
        /// <summary>
        /// Page_Load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            SXT.Party.Utility.PageUtility.CheckLogin(this);
            if (!this.Page.IsPostBack)
            {
                this.BindData();
                this.LoadData();
            }
        }
        #endregion

        #region 数据访问
        /// <summary>
        /// BindData
        /// </summary>
        protected override void BindData()
        {
            //this.cbStatus.Enabled = this.CheckRight("Audit");
            //this.lbStatus.Visible = this.cbStatus.Visible = ModuleUtil.IsRootBranchMember(this.CurrentUser.LoginID);

            string parentBranchID = SXT.Party.Utility.PartyOrg.QueryParentBranchID(this.BranchID);
            if (string.IsNullOrEmpty(parentBranchID))
                this.cblPublishRange.Items[0].Attributes.Add("style", "display:none");
            else
            {
                this.cblPublishRange.Items[0].Text = string.Format("推送到\"{0}\"的首页(点“发布”时推送，需审核)", SXT.Party.Utility.PartyOrg.QueryBranchName(parentBranchID));
                this.cbShowInHomePage.Enabled = false;
            }


            if (Request.QueryString["IsAudit"] != null)
            {
                this.btnSave.Visible = false;
                this.btnSaveClose.Visible = false;
                this.btnClose.ClientScript = "return window.close();";
                this.baseTarget.Visible = true;
                this.btnEnsure.Visible = false;
                this.btnAgree.Visible = true;
                this.btnDisagree.Visible = true;
            }
            else
            {
                this.btnClose.ClientScript = CloseDialogScript();
            }

            if (!this.PageSign.Equals("BranchTrends"))
            {
                this.btnEnsure.Visible = false;
            }

            if (ModuleUtil.IsAdmin(this.CurrentUser.LoginID))
            {
                this.btnEnsure.Visible = false;
            }

            SXT.Utility.Business.ControlBinding(this.ddlThematic, SXT.Party.PartyAdmin.Model.PartyThematicManage.GetGridData("","True"), "Title", "ID", false);
            this.ddlThematic.Items.Insert(0, new ListItem() { Text = "普通活动", Value = "" });
            //最顶层显示推送到第三方
            if (this.BranchID == PartyOrg.QueryTopBranchID())
            {
               
                trPush.Visible = true;
                PageUtility.SystemParameterBinding(this.checkPush, PartyEnums.SystemParameterType.PushToOtherList);
                //没有配参数，不显示
                trPush.Visible = this.checkPush.Items.Count > 0;
            }

        }
        /// <summary>
        /// LoadData
        /// </summary>
        protected override void LoadData()
        {
            if (!string.IsNullOrEmpty(this.KeyID))
            {
                Model.WorkTrends oModel = new Model.WorkTrends();
                oModel.ID = this.KeyID;
                oModel.Load();

                this.txtTitle.Text = oModel.Title;
                this.ckContent.Text = oModel.Content;
                this.cbShowInHomePage.Checked = oModel.ShowInHomePage != null ? Convert.ToBoolean(oModel.ShowInHomePage) : false;
                this.cbStatus.Checked = oModel.Status != null ? Convert.ToBoolean(oModel.Status) : false;
                this.cbIsFirst.Checked = oModel.IsFirst != null ? Convert.ToBoolean(oModel.IsFirst) : false;
                this.cbIsTop.Checked = oModel.IsTop != null ? Convert.ToBoolean(oModel.IsTop) : false;
                this.ppBranch.Value = oModel.BranchID;
                this.ppBranch.Text = SXT.Party.Utility.PartyOrg.QueryBranchName(oModel.BranchID);
                this.hdFileID.Value = oModel.ImageID;
                this.lnkFileName.HRef = SXT.Utility.FileServer.QueryFileUrl(oModel.ImageID);
                this.lbFileName.InnerText = SXT.Utility.FileServer.QueryFileName(this.hdFileID.Value);

                this.dtActivityTime.Text = oModel.ActivityTime.ToString("yyyy-MM-dd");
                this.cblPublishRange.Items[0].Selected = oModel.IsPublishHL.BitToBool();
                this.cbSuperTop.Checked = Convert.ToInt32(oModel.SuperTop) == 1;
                this.ppBranch.Enabled = false;
                this.ddlThematic.SelectedValue = oModel.Thematic;
                if (oModel.Status.ToBool())
                {
                    //this.btnEnsure.Enabled = false;
                    this.cblPublishRange.Enabled = false;
                }
            }
            else
            {
                this.ppBranch.Value = this.BranchID;
                this.ppBranch.Text = SXT.Party.Utility.PartyOrg.QueryBranchName(this.ppBranch.Value);
                this.ppBranch.Enabled = false;
            }
        }

        /// <summary>
        /// SaveData
        /// </summary>
        protected void SaveData(bool isClose, bool status = false)
        {
            bool bResult = false;
            Model.WorkTrends oModel = new Model.WorkTrends();
            oModel.ID = this.KeyID;
            oModel.Load();
            oModel.Title = this.txtTitle.Text;
            oModel.Content = this.ckContent.Text;
            oModel.ShowInHomePage = true;//this.cbShowInHomePage.Checked;
            oModel.Status = this.cbStatus.Checked;
            oModel.IsTop = this.cbIsTop.Checked;
            oModel.IsFirst = this.cbIsFirst.Checked;
            oModel.BranchID = this.ppBranch.Value;
            oModel.ImageID = this.hdFileID.Value;
            oModel.ActivityTime = Convert.ToDateTime(this.dtActivityTime.Text);
            oModel.IsPublishHL = this.cblPublishRange.Items[0].Selected;
            oModel.CreateBranchID = this.ppBranch.Value;
            oModel.SuperTop = this.cbSuperTop.Checked ? 1 : 0;

            oModel.Thematic = this.ddlThematic.SelectedValue;
            //检查是否重复
            if (!SXT.Utility.Business.CheckFieldUnique(oModel.TableName, "Title", this.txtTitle.Text.Trim(),
                string.Format("ID <> '{0}' AND BranchID = '{1}' ", this.KeyID, this.ppBranch.Value)))
            {
                this.AlertMessage("已存在相同的组织动态，请确认后再重试！");
                return;
            }

            string id = this.KeyID;
            if (string.IsNullOrEmpty(this.KeyID))
            {
                id = Common.NewGuid;
            }
            if (oModel.ShowInHomePage == true && oModel.Status == true && oModel.IsPushToMobile != "1")
            {
                try
                {
                    string url = "http://" + HttpContext.Current.Request.Url.Host + "/MS/MobileInterfaceService.asmx";
                    SXT.Party.Utility.PushDaoyiClient mis = new SXT.Party.Utility.PushDaoyiClient();
                    mis.PushInformation(id, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), CurrentUser.UserName, oModel.Title, "2");
                    oModel.IsPushToMobile = "1";
                }
                catch
                {
                }
            }

            if (!string.IsNullOrEmpty(this.KeyID))
            {
                oModel.ModifyBy = this.CurrentUser.LoginID;
                oModel.ModifyTime = DateTime.Now;
                oModel.ID = this.KeyID;
                bResult = oModel.Update(this.PageID);
            }
            else
            {
                oModel.ID = this.PrimaryKeyID = id;
                oModel.CreateBy = this.CurrentUser.LoginID;
                oModel.CreateTime = DateTime.Now;
                bResult = oModel.Insert(this.PageID);
            }

            if (bResult)
            {
                ////推送到第三方 天河区委
                if (oModel.ShowInHomePage.ToBool() && oModel.Status.ToBool() && oModel.BranchID == PartyOrg.QueryTopBranchID())
                {
                    oModel.Content = Server.HtmlEncode(oModel.Content);
                    string content = PageUtility.ObjListToXml<Model.WorkTrends>(new List<Model.WorkTrends>() { oModel });
                    var push = GetPushToOtherList();
                    if (push.Count() > 0)
                    {
                        PartyPush.Add(oModel.ID, "", oModel.TableName, PartyPush.PushSourceOperation.Update, push.ToArray(), 
                            content, "", this.CurrentUser.LoginID,oModel.Title);
                    }
                }
                this.RefreshSign = true; //设置刷新标识
                if (isClose)
                {
                    this.CloseDialog(); //关闭窗口
                }
                else
                {
                    string url = "../../../../../Portal/BranchPortal.aspx?../Widgets/Pages/WorkTrends/WorkTrends.aspx?ID=" + oModel.ID + "&BranchID=" + oModel.BranchID;
                    Response.Write("<script>window.open('" + url + "','_blank')</script>");
                }
            }
        }
        /// <summary>
        /// 获取推送到第三方列表
        /// </summary>
        /// <returns></returns>
        private List<string> GetPushToOtherList()
        {
            List<string> list = new List<string>();
            foreach (ListItem item in checkPush.Items)
            {
                if (item.Selected)
                {
                    list.Add(item.Value);
                }
            }
            return list;
        }


        //发布到上级
        private void PublishHightLevel()
        {
            if (this.cblPublishRange.Items[0].Selected)
            {
                if (Model.WorkTrends.QueryUnique(this.txtTitle.Text, SXT.Party.Utility.PartyOrg.QueryParentBranchID(this.BranchID)))
                {
                    //发布到上级组织
                    Model.WorkTrends oModelCopy = new Model.WorkTrends();
                    oModelCopy.ID = this.KeyID;
                    oModelCopy.Load();
                    oModelCopy.ID = SXT.Utility.Common.NewGuid;
                    oModelCopy.BranchID = SXT.Party.Utility.PartyOrg.QueryParentBranchID(this.BranchID);
                    oModelCopy.ShowInHomePage = true;
                    oModelCopy.IsPublishHL = false;
                    oModelCopy.Status = false;
                    oModelCopy.Insert(this.PageID);
                    //发送组织待办
                    //SXT.Party.Utility.PartyTask.AddTask(oModelCopy.ID, txtTitle.Text,
                    //"组织动态", SSOClient.CurrentUser.LoginID,
                    //new string[] { oModelCopy.BranchID }, "http://" + Request.Url.Host + "/admin/Project/PartyAdmin/Module/WorkTrends/WorkTrendsEdit.aspx?ID=" + oModelCopy.ID + "&BranchID=" + oModelCopy.BranchID + "&IsAudit=true",
                    //SXT.Party.Utility.PartyTask.TaskSpecie.Branch, "下级组织");
                    SXT.Party.Utility.PartyTask.AddTask(oModelCopy.ID, txtTitle.Text,
                    "组织动态", SSOClient.CurrentUser.LoginID,
                    new string[] { oModelCopy.BranchID }, "../../../PartyAdmin/Module/WorkTrends/WorkTrendsEdit.aspx?ID=" + oModelCopy.ID + "&BranchID=" + oModelCopy.BranchID + "&IsAudit=true",
                    SXT.Party.Utility.PartyTask.TaskSpecie.Branch, "下级组织");
                }
            }
        }
        #endregion

        #region 按钮事件
        /// <summary>
        /// 保存按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            this.SaveData(false);
        }

        /// <summary>
        /// 保存并关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSaveAndClose_Click(object sender, EventArgs e)
        {
            this.SaveData(true);
        }

        /// <summary>
        /// 保存并关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnEnsure_Click(object sender, EventArgs e)
        {
            this.SaveData(true, true);
            this.PublishHightLevel();
            //if (this.cbStatus.Checked)
            //{
            //    this.SaveData(true);
            //    this.PublishHightLevel();
            //}
            //else
            //{
            //    if (Request.QueryString["IsAudit"] != null)
            //    {
            //        Model.WorkTrends oModelCopy = new Model.WorkTrends();
            //        oModelCopy.ID = this.KeyID;
            //        oModelCopy.Delete();
            //    }
            //}
            //if (Request.QueryString["IsAudit"] != null)
            //{
            //    SXT.Party.Utility.PartyTask.TaskDone(this.KeyID, this.CurrentUser.LoginID);
            //    this.ClientScript.RegisterClientScriptBlock(this.GetType(), "close", "window.close();", true);
            //}
        }

        protected void btnDisagree_Click(object sender, EventArgs e)
        {
            Model.WorkTrends oModelCopy = new Model.WorkTrends();
            oModelCopy.ID = this.KeyID;
            oModelCopy.Delete();

            SXT.Party.Utility.PartyTask.TaskDone(this.KeyID, this.CurrentUser.LoginID);
            this.ClientScript.RegisterClientScriptBlock(this.GetType(), "close", "window.close();", true);
        }

        protected void btnAgree_Click(object sender, EventArgs e)
        {
            Model.WorkTrends oModel = new Model.WorkTrends();
            oModel.ID = this.KeyID;
            oModel.Title = this.txtTitle.Text;
            oModel.Content = this.ckContent.Text;
            oModel.ShowInHomePage = this.cbShowInHomePage.Checked;
            oModel.Status = true;
            //oModel.Status = this.cbStatus.Checked;
            oModel.IsFirst = this.cbIsFirst.Checked;
            oModel.BranchID = this.ppBranch.Value;
            oModel.ImageID = this.hdFileID.Value;
            oModel.ActivityTime = Convert.ToDateTime(this.dtActivityTime.Text);
            oModel.IsPublishHL = this.cblPublishRange.Items[0].Selected;
            oModel.Update();
            this.PublishHightLevel();
            SXT.Party.Utility.PartyTask.TaskDone(this.KeyID, this.CurrentUser.LoginID);
            this.ClientScript.RegisterClientScriptBlock(this.GetType(), "close", "window.close();", true);
        }
        #endregion

        [WebMethod]
        public static string LoadImageUrl(string id)
        {
            return SXT.Utility.FileServer.QueryFileUrl(id);
        }

        protected override void RegisterLoadingScript()
        {
            if (this.Request.QueryString["IsAudit"] == null)
                base.RegisterLoadingScript();
        }

        protected override void RegisterMacthDialogContentSizeScript()
        {
            if (this.Request.QueryString["IsAudit"] == null)
                base.RegisterMacthDialogContentSizeScript();
        }

    }
}